console.log('load common.js v0.1')

/**
 * 睡眠
 * @param {int} ms 
 * @returns 
 */
function sleep(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

/**
 * 获取dom
 * @param selected
 * @param condition 自定义校验
 * @returns {Promise<*>}
 */
async function querySelector(selected, condition) {
    while (true) {
        await sleep(300);
        let res = document.querySelector(selected);
        if (condition) {
            if (condition(res)) return res;
        } else {
            if (res) return res;
        }
    }
}

/**
 * 获取dom
 * @param selected
 * @param condition 自定义校验
 * @returns {Promise<*>}
 */
async function querySelectorAll(selected, condition) {
    while (true) {
        await sleep(300);
        let res = document.querySelectorAll(selected);
        if (condition) {
            if (condition(res)) return res;
        } else {
            if (res) return res;
        }
    }
}

// 点击dom
async function clickOfSelected(selected) {
    let node = await querySelector(selected);
    node.click();
}

async function fetchReturnText(url) {
    let xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            let res = xmlhttp.responseText;
            console.log(res);
            copy(res);
        }
        if (xmlhttp.readyState === 4 && xmlhttp.status !== 200) {
            alert('请求出错：' + url);
        }
    }
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

function copy(text) {
    const input = document.createElement('textarea');
    document.body.appendChild(input);
    input.value = text;
    input.select();
    document.execCommand("Copy");
}

function post(url, data, success) {
    let xhr = new XMLHttpRequest();
    data = JSON.stringify(data);
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            // 请求成功
            success(xhr.responseText);
        }
    };
    xhr.send(data);
}

function sendInfoMsg(msg) {
    fetch("http://localhost:8082/wxWebhook/sendMsg?msg=" + msg);
}

function sendErrorMsg(msg) {
    fetch("http://localhost:8082/wxWebhook/sendMsg?msg=" + msg);
}

function getGridConfigList() {
    let res = [];
    for (let i = 0; i < localStorage.length; i++) {
        if (localStorage.key(i).startsWith('grid_config')) {
           res.push(JSON.parse(localStorage.getItem(localStorage.key(i))));
        }
    }
    return res;
}

function updateGridConfigByStockCode(gridConfig) {
    for (let i = 0; i < localStorage.length; i++) {
        let key = localStorage.key(i);
        if (s.startsWith('grid_config')) {
            if (JSON.parse(localStorage.getItem(s)).stockCode === gridConfig.stockCode) {
                localStorage.setItem(key, gridConfig);
            }
        }
    }
}

function pushBuyQueue(buyQueue) {
    localStorage.setItem('buyQueue_' + new Date().getTime(), buyQueue);
    sendInfoMsg(`写入买入委托队列：${buyQueue.stockCode} 价格：${buyQueue.price} 数量：${buyQueue.num}`);
}

function pushSellQueue(buyQueue) {
    localStorage.setItem('sellQueue_' + new Date().getTime(), buyQueue);
    sendInfoMsg(`写入卖出委托队列：${buyQueue.stockCode} 价格：${buyQueue.price} 数量：${buyQueue.num}`);
}

/**
 * 小数减法
 */
function subtraction(n1, n2) {
    return String((Number.parseInt(n1 * 1000) - Number.parseInt(n2 * 1000)) / 1000).toString();
}

function addition(n1, n2) {
    return String((Number.parseInt(n1 * 1000) + Number.parseInt(n2 * 1000)) / 1000).toString();
}
